const alert = (message) => {
  if(typeof message === 'string') {
    let content = message;
    message = {
      type: 'right',
      content
    }
  } else if(typeof message === 'object') {
    message.type = String(message.type);
    message.content = String(message.content);
  } else {
    console.error('alert: message-${message} is not a string or object');
    message = {
      type: "error",
      content: 'unknown error'
    }
  }

  let alertCardWrapper = document.getElementById('alertCardWrapper');
  let alertCard = alertCardWrapper.firstChild,
    alertIcon = document.getElementById('alertIcon'),
    alertContent = document.getElementById('alertContent');
  
  let className = message.type === 'error' ? 'icon-cancel' : 'icon-right';
  alertIcon.classList.add(className);
  alertContent.innerText = message.content;

  return new Promise((resolve) => {
    alertCardWrapper.classList.add('fadeIn');
    setTimeout(() => {
      resolve();
    }, 1200);
  }).then(() => {
    alertCardWrapper.classList.remove('fadeIn');
    return new Promise(resolve => {
      setTimeout(() => {
        resolve();
      }, 500);
    })
  })
}

const confirm = (message, cb) => {
  if(typeof message !== 'string') {
    console.error(`confirm: message-${message} is not a string return`);
    return;
  }

  let confirmCardWrapper = document.getElementById('confirmCardWrapper'),
    confirmContent = document.getElementById('confirmContent'),
    sureButton = document.getElementById('sureButton'),
    cancelButton = document.getElementById('cancelButton');

  confirmContent.innerText = message;

  return new Promise(resolve => {
    confirmCardWrapper.classList.add('fadeIn');

    let sureFunc = () => {
      confirmCardWrapper.classList.remove('fadeIn');
      sureButton.removeEventListener('click', sureFunc);
      resolve(true);
    }
    let cancelFunc = () => {
      confirmCardWrapper.classList.remove('fadeIn');
      sureButton.removeEventListener('click', sureFunc);
      resolve(false);
    }
    sureButton.addEventListener('click', sureFunc);
    cancelButton.addEventListener('click', cancelFunc);
  })
}

const progress = (show, ratio) => {
  if(typeof show !== 'boolean' || typeof ratio !== 'number' || ratio > 1 || ratio < 0) {
    console.error(`progress, show-${show}, ratio-${ratio}, wrong parameter`);
    return;
  }
  let progressBarWrapper = document.getElementById('progressBarWrapper');
  let progressLineHover = document.getElementById('progressLineHover');

  if(show) {
    progressBarWrapper.classList.add('fadeIn');
    progressLineHover.style.width = ratio * 100 + '%';
  } else {
    progressBarWrapper.classList.remove('fadeIn');
    progressLineHover.style.width = 0;
  }
}

export {
  alert,
  confirm,
  progress
};